package ws_handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	uuid "github.com/satori/go.uuid"
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/log"
	"peilian-api/utils/format"
	ws "peilian-api/utils/websocket"
)

// 客户端连接
func WsClient(context *gin.Context) {
	sessionID := context.Param("sessionId")
	session, err := GetSessionObj(sessionID)
	if err != nil {
		format.NewResponseJson(context).Error(51001)
		return
	}

	upGrande := websocket.Upgrader{
		//设置允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	//创建连接
	conn, err := upGrande.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		log.Logger.InfoMsgF(context, fmt.Sprintf("websocket connect error: %s", context.Param("channel")))
		format.NewResponseJson(context).Error(51001)
		return
	}

	//生成唯一标识client_id
	var uid = uuid.NewV4().String()
	var bus = ws.Business{
		Session: session,
	}
	client := &ws.Client{
		Id:      uid,
		Socket:  conn,
		AudioCh: make(chan []byte, 1024),
		TextCh:  make(chan string, 1024),
		Message: make(chan []byte, 1024),
		Bus:     bus,
		Ctx:     context,
		Logger: &log.MyLogger{
			Zlog: log.InitLogger(fmt.Sprintf("logs/%d.log", session.ID)),
		},
	}
	switch session.Career.ReportType {
	case "web":
		nextRealize := &ws.Recommend{Client: client}
		if session.CareerID == tables.QCommonId {
			nextRealize.IRecommend = &ws.CommonCareer{}
		} else {
			nextRealize.IRecommend = &ws.OccupationCareer{}
		}
		client.INextQuestion = nextRealize
	case "custom", "none":
		client.INextQuestion = &ws.CustomClient{Client: client}
	case "pdf":
		client.INextQuestion = &ws.DefaultClient{Client: client}
	default:
		format.NewResponseJson(context).Err(http.StatusBadRequest, "暂不支持该岗位面试")
		return
	}
	b, _ := json.Marshal(bus.Session)
	log.Logger.InfoF(context, fmt.Sprintf("websocket client info: %+v, interview sessions info:%s", client, string(b)))
	//注册
	ws.WsManager.RegisterClient(client)

	//起协程，实时接收和回复数据
	go func() {
		defer client.RecoverGoroutineCtx()
		client.Read()
	}()
	go func() {
		defer client.RecoverGoroutineCtx()
		client.Write()
	}()
}

// 专项练习websocket客户端连接

func SpecialWsClient(context *gin.Context) {
	sid := context.Param("sid")
	specialRecord, err := GetSpecialObj(sid)
	if err != nil {
		log.Logger.InfoF(context, fmt.Sprintf("GetSpecialObj err, msg: %s", err.Error()))
		format.NewResponseJson(context).Error(51000)
		return
	}

	upGrande := websocket.Upgrader{
		//设置允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	//升级get请求为websocket协议
	conn, err := upGrande.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		log.Logger.InfoF(context, fmt.Sprintf("websocket connect error: %s, upgrade: %s", context.Param("channel"), err.Error()))
		format.NewResponseJson(context).Error(51001)
		return
	}

	//生成唯一标识client_id
	var uid = uuid.NewV4().String()
	var bus = ws.Business{
		SpecialRecord:   specialRecord,
		CurrentQuestion: specialRecord.Question,
	}
	client := &ws.Client{
		Id:      uid,
		Socket:  conn,
		AudioCh: make(chan []byte, 1024),
		TextCh:  make(chan string, 1024),
		Message: make(chan []byte, 1024),
		Bus:     bus,
		Ctx:     context,
		Logger: &log.MyLogger{
			Zlog: log.InitLogger(fmt.Sprintf("logs/special_%d.log", specialRecord.ID)),
		},
	}
	client.INextQuestion = &ws.DefaultClient{Client: client}
	b, _ := json.Marshal(bus.SpecialRecord)
	log.Logger.InfoF(context, fmt.Sprintf("websocket client info: %+v, interview special_record info:%s", client, string(b)))
	//注册
	ws.WsManager.RegisterClient(client)

	//起协程，实时接收和回复数据
	go func() {
		defer client.RecoverGoroutineCtx()
		client.Read()
	}()
	go func() {
		defer client.RecoverGoroutineCtx()
		client.Write()
	}()
}
